<template>
  <div class="login-wrapper">
      <div class="login-container">
          <div class="form-header">
              <h2>用户登录</h2>
              <p>欢迎使用IoT系统</p>
          </div>
          <form @submit.prevent="handleLogin" class="floating-form">
              <div class="input-group">
                  <input id="username" v-model.trim="loginForm.username" type="text" autocomplete="off" @input="validateInput" required />
                  <label for="username">用户名</label>
                  <span class="highlight"></span>
              </div>
              <div class="input-group">
                  <input id="password" v-model.trim="loginForm.password" type="password" autocomplete="off" @input="validateInput" required />
                  <label for="password">密码</label>
                  <span class="highlight"></span>
              </div>
              <div class="error-message" v-if="errorMsg">{{ errorMsg }}</div>
              <button type="submit" class="submit-btn" :disabled="!isFormValid">
                  <span>登录</span>
                  <i class="arrow-icon"></i>
              </button>
          </form>
      </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const isLoading = ref(false) // 新增加载状态

// 表单数据
const loginForm = reactive({
  username: 'admin',
  password: '123456'
})

const errorMsg = ref('')
const isFormValid = ref(false)

// 输入验证
const validateInput = () => {
  // 基本验证
  if (loginForm.username && loginForm.password) {
      isFormValid.value = true
      errorMsg.value = ''
  } else {
      isFormValid.value = false
  }
}

// 登录处理
const handleLogin = async () => {
  try {
    isLoading.value = true
    
    // 调用后端接口验证
    const response = await fetch('http://localhost:8082/api/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: loginForm.username,
        password: loginForm.password
      })
    })

    if (!response.ok) {
      throw new Error(await response.text())
    }

    // const data = await response.json()
    
    // 存储Token
    // localStorage.setItem("authToken", data.token)
    localStorage.setItem("isLogin", true)

    // 跳转前清除加载状态
    isLoading.value = false
    router.push('/home')
  } catch (err) {
    console.error('登录失败:', err)
    errorMsg.value = err.message || '登录失败，请检查凭证'
    isLoading.value = false
  }
}
// 登录处理（静态）
// const handleLogin = async () => {
//   // 防止XSS攻击
//   const xssPattern = /(~|\{|\}|"|'|<|>|\?)/g
//   if (xssPattern.test(loginForm.username) || xssPattern.test(loginForm.password)) {
//       errorMessage('警告:输入内容包含非法字符');
//       return
//   }

//   // 验证用户名和密码
//   if (loginForm.username === 'admin' && loginForm.password === '123456') {
//       // 对输入进行转义处理
//       const safeUsername = encodeURIComponent(loginForm.username)
//       const safePassword = encodeURIComponent(loginForm.password)
      
//       console.log('登录请求:', { username: safeUsername, password: safePassword })

//       // 模拟登录成功并设置cookie
//       const expires = new Date(Date.now() + 3600 * 1000).toUTCString()
//       document.cookie = `authToken=yourAuthToken; path=/; expires=${expires}`

//       localStorage.setItem("isLogin", true)

//       // 跳转到主页
//       router.push('/home')
//   } else {
//       throw new Error('用户名或密码错误')
//   }
  
// }


// 错误提示
const errorMessage = (text) => {
  errorMsg.value = text
  setTimeout(() => {
      errorMsg.value = ''
  }, 3000)
}

onMounted(() => {
  validateInput()
})

</script>

<style scoped>
.login-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-container {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 20px;
}

.login-container {
  width: 100%;
  background: white;
  border-radius: 20px;
  padding: 40px;
  padding-right: 80px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.form-header {
  text-align: center;
  margin-bottom: 40px;
}

.form-header h2 {
  color: #2c3e50;
  font-size: 32px;
  margin-bottom: 10px;
  font-weight: 700;
}

.form-header p {
  color: #95a5a6;
  font-size: 16px;
}

.floating-form .input-group {
  position: relative;
  margin-bottom: 30px;
}

.input-group input {
  width: 100%;
  padding: 15px;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  font-size: 16px;
  transition: all 0.3s ease;
  background: transparent;
  color: #333;
}

.input-group label {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  background: white;
  padding: 0 5px;
  color: #95a5a6;
  font-size: 16px;
  transition: all 0.3s ease;
  pointer-events: none;
}

.input-group input:focus,
.input-group input:valid {
  border-color: #3498db;
}

.input-group input:focus + label,
.input-group input:valid + label {
  top: 0;
  font-size: 14px;
  color: #3498db;
}

.submit-btn {
  width: 100%;
  padding: 15px;
  margin-left: 15px;
  background: linear-gradient(to right, #3498db, #2980b9);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
}

.arrow-icon {
  border: solid white;
  border-width: 0 2px 2px 0;
  display: inline-block;
  padding: 3px;
  transform: rotate(-45deg);
}

.form-footer {
  text-align: center;
  margin-top: 20px;
  color: #95a5a6;
}

.form-footer a {
  color: #3498db;
  text-decoration: none;
  margin-left: 5px;
  font-weight: 600;
}

.form-footer a:hover {
  text-decoration: underline;
}

.error-message {
  color: #f56c6c;
  font-size: 14px;
  text-align: center;
  margin-bottom: 20px;
}

/* 添加加载状态样式 */
.submit-btn[disabled] {
  opacity: 0.7;
  cursor: not-allowed;
}

</style>